package com.ssjy.atms.common;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.jfinal.config.*;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.SqlServerDialect;
import com.jfinal.plugin.cron4j.Cron4jPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.template.Engine;
import com.ssjy.atms._admin.HomeController;

import java.sql.Connection;

/**
 * Created by wendell on 2017/1/24.
 */
public class AtmsConfig extends JFinalConfig {
    private static Prop p = loadConfig();
    private WallFilter wallFilter;

    @Override
    public void configConstant(Constants me) {
        me.setDevMode(p.getBoolean("devMode", false));
        me.setJsonFactory(MixedJsonFactory.me());
    }

    @Override
    public void configRoute(Routes me) {
        me.add("/", HomeController.class);
    }

    @Override
    public void configEngine(Engine me) {

    }

    @Override
    public void configPlugin(Plugins me) {
        DruidPlugin druidPlugin = getDruidPlugin();
        wallFilter = new WallFilter();              // 加强数据库安全
        wallFilter.setDbType("sqlserver");
        druidPlugin.addFilter(wallFilter);
        druidPlugin.addFilter(new StatFilter());    // 添加 StatFilter 才会有统计数据
        me.add(druidPlugin);

        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        arp.setDialect(new SqlServerDialect());
        arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
        //_MappingKit.mapping(arp);
        // 强制指定复合主键的次序，避免不同的开发环境生成在 _MappingKit 中的复合主键次序不相同
        arp.setPrimaryKey("document", "mainMenu,subMenu");
        me.add(arp);
        if (p.getBoolean("devMode", false)) {
            arp.setShowSql(true);
        }

        me.add(new EhCachePlugin());
        me.add(new Cron4jPlugin(p));
    }

    @Override
    public void configInterceptor(Interceptors me) {

    }

    @Override
    public void configHandler(Handlers me) {

    }

    private static Prop loadConfig() {
        try {
            // 优先加载生产环境配置文件
            return PropKit.use("ssjy_atms_config_pro.txt");
        } catch (Exception e) {
            // 找不到生产环境配置文件，再去找开发环境配置文件
            return PropKit.use("ssjy_atms_config_dev.txt");
        }
    }

    /**
     * 抽取成独立的方法，例于 _Generator 中重用该方法，减少代码冗余
     */
    public static DruidPlugin getDruidPlugin() {
        return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
    }
}
